<template>
  <div class="box">
    <div class="search">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="">
          <el-input v-model="formInline.username" placeholder="请输入管理员名称" size="mini" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" size="mini">查找</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true" size="mini">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportToExcel" size="mini">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <template>
        <el-table :data="tableData" style="width: 100%" border>
          <el-table-column label="管理员ID" width="239" sortable>
            <template slot-scope="scope">

              <span style="margin-left: 10px">{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="管理员名称" width="239">
            <template slot-scope="scope">

              <span style="margin-left: 10px">{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column label="管理员头像" width="239">
            <template slot-scope="scope">

              <img :src=scope.row.avatar style="margin-left: 10px;width: 40px;height: 40px;">
            </template>
          </el-table-column>
          <el-table-column label="管理员角色" width="239">
            <template slot-scope="scope">

              <!-- <span style="margin-left: 10px">{{  }}</span> -->
              <el-tag v-for="(item, index) in handle(scope.row.roleIds)" :key="index"
                style="margin: 5px; padding: 3px 8px; font-size: 12px;">{{ item }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
    <div class="block">

      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage4" :page-sizes="[5, 10, 15, 20]" :page-size=Number(this.pageSize)
        layout="total, sizes, prev, pager, next, jumper" :total=Number(this.total)>
      </el-pagination>
    </div>

    <el-dialog title="创建" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="管理员名称" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员头像" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" action="api/admin/storage/create" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="管理员角色" :label-width="formLabelWidth">
          <el-select v-model="form.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="adds">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="dialogFormVisible2">
      <el-form :model="form">
        <el-form-item label="管理员名称" :label-width="formLabelWidth">
          <el-input v-model="forms.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" :label-width="formLabelWidth">
          <el-input v-model="forms.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员头像" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" action="api/admin/storage/create" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="forms.avatar" :src="forms.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="管理员角色" :label-width="formLabelWidth">
          <el-select v-model="forms.roleIds" multiple placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="change">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
const XLSX = require('xlsx');
import { yonghu, tianjia, shanchu, bianji } from '@/api/xtgl/gly.js';
export default {
  name: 'DocumentsAdmin',

  data() {
    return {
      forms: {

      },
      options: [{
        value: '1',
        label: '超级管理员'
      }, {
        value: '2',
        label: '商场管理员'
      }, {
        value: '3',
        label: '推广管理员'
      }, {
        value: '6',
        label: 'wrk'
      }, {
        value: '7',
        label: 'ljj'
      }, {
        value: '8',
        label: '123'
      }, {
        value: '9',
        label: '22'
      }],
      imageUrl: '',
      dialogFormVisible: false,
      dialogFormVisible2: false,
      form: {
        username: '',
        password: '',
        avatar: '',
        roleIds: [],

      },
      formLabelWidth: '120px',
      pageSize: '20',
      total: '',
      currentPage4: 1,
      tableData: [],
      formInline: {
        username: '',
      }
    };
  },

  mounted() {
    this.show()
  },

  methods: {
    exportToExcel() {
      // 创建一个工作簿对象
      let workbook = XLSX.utils.book_new();

      // 定义表头
      const headers = ['管理员ID', '管理员名称', '管理员头像', '管理员角色'];

      // 从 tableData 中提取数据并转换为数组
      const data = this.tableData.map(row => [
        row.id,
        row.username,
        row.avatar,
        row.roleIds,
        
      ]);

      // 在数据数组开头插入表头
      data.unshift(headers);

      // 创建一个工作表对象
      let worksheet = XLSX.utils.aoa_to_sheet(data);

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 导出Excel文件
      XLSX.writeFile(workbook, '管理员.xlsx');
    },
    change() {
      const reverseRoleMap = {};
      this.options.forEach(option => {
        reverseRoleMap[option.label] = option.value;
      });
      const digitalRoleIds = this.forms.roleIds.map(role => reverseRoleMap[role] || 0);
      const formDataToSubmit = {
        ...this.forms,
        roleIds: digitalRoleIds
      };
      bianji(formDataToSubmit).then((res) => {
        console.log(res);
        if (res.errmsg == '成功') {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success'
          });
          this.show()
          this.dialogFormVisible2 = false
        }
      })
     
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handle(roleIds) {
      const roleMap = {
        1: '超级管理员',
        2: '商场管理员',
        3: '推广管理员',
        4: 'wrk',
        5: 'ljj',
        6: '123',
        7: '22'
      };
      return roleIds.map(roleId => roleMap[roleId] || '未知角色');
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.show()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val
      this.show()
    },
    show() {
      yonghu({
        page: this.currentPage4,
        limit: this.pageSize,
        sort: 'add_time',
        order: 'desc'
      }).then((res) => {
        console.log(res);
        this.tableData = res.data.list
        this.total = res.data.total
      })
    },
    handleEdit(index, row) {
      console.log(index, row);
      const roleMap = {
        1: '超级管理员',
        2: '商场管理员',
        3: '推广管理员',
        4: 'wrk',
        5: 'ljj',
        6: '123',
        7: '22'
      };
      const convertedRoleIds = row.roleIds.map(roleId => roleMap[roleId] || '未知角色');
      this.forms = {
        ...row,
        roleIds: convertedRoleIds
      };
      this.dialogFormVisible2 = true;
    },
    handleDelete(index, row) {
      console.log(index, row);
      shanchu({
        ...row
      }).then((res) => {
        console.log(res);
        if (res.errmsg == '成功') {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success'
          });
          this.show()
        }
      })
    },
    onSubmit() {
      yonghu({
        page: 1,
        limit: this.pageSize,
        sort: 'add_time',
        order: 'desc',
        username: this.formInline.username
      }).then((res) => {
        console.log(res);
        this.tableData = res.data.list
        this.total = res.data.total
      })
    },
    adds() {
      tianjia({
        ...this.form
      }).then((res) => {
        console.log(res);
        if (res.errmsg == '成功') {
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success'
          });
          this.show()
          this.dialogFormVisible = false
        }
      })

    },
  },
};
</script>
<style scoped>
.box {
  padding: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>